import React, { PureComponent } from 'react';
import './index.css'

// Component只要执行setState, 不改变数据也会再次render(), 且子组件也会跟着render()
// 原因: shouldComponentUpdate()总是返回true
// 解决方法: 重写shouldComponentUpdate方法, 或改用PureComponent, 但PureComponent只对比地址, 更改时应该返回新的引用
class Parent extends PureComponent {

    state = {name: 'lili'}

    changeName = () => {
        this.setState({name: 'lala'})
        
        // 修改数组时, 应该用[...]的方式
        // 下面这样做是浅拷贝, 地址还相同, 没有修改
        // const obj = this.state
        // obj.name = 'lala'
        // this.setState(obj)
    }

    // shouldComponentUpdate(nextProps, nextState) {
    //     console.log(this.props, this.state);
    //     console.log(nextProps, nextState);
    //     return !(this.state.name === nextState.name)
    // }

    render() {
        const { name } = this.state
        console.log('Parent render');
        return (
            <div className='parent'>
                <h3>I am Parent, name is {name}</h3>
                <button onClick={this.changeName}>Click me change</button>
                {/* <Child name={name}/> */}
            </div>
        );
    }
}
class Child extends PureComponent {

    // shouldComponentUpdate(nextProps, nextState) {
    //     console.log(this.props, this.state);
    //     console.log(nextProps, nextState);
    //     return !(this.props.name === nextProps.name)
    // }

    render() {
        const { name } = this.props
        console.log('Child render');
        return (
            <div className='child'>
                <h3>I am Child, name is {name}</h3>
            </div>
        );
    }
}
export default Parent;